
/*

Promise初始状态 pending
resolve() -> fulfilled 完成
reject()  -> rejected 错误 拒绝


const p = Promise.all([p1, p2, p3])
p1 && p2 && p3 === -> fulfilled
如果有一个rejected，导致p->rejected

const p = Promise.any([p1, p2, p3])
如果有一个fulfilled，p->fulfilled
p1 && p2 && p3都rejected， p->rejected

const p = Promise.race([p1, p2, p3])
p1, p2, p3 谁快（不管成功还是错误）谁决定p的状态
*/

const myAjax = ({ method = "GET", url }) => {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest()
		xhr.open(method, url)
		xhr.send()
		xhr.responseType = "json"
		xhr.onreadystatechange = function() {
			if(xhr.readyState === 4) {
				if(xhr.status === 200) {
					// success(xhr.response)
					resolve(xhr.response)
				} else {
					// error(xhr.response)
					reject(xhr.statusText)
				}
			}
		}
	})
}
/*
myAjax({
	url: "http://yizhanketang.com:1010/api/v1/bmi34567"
}).then((res) => {
	console.log(res)
}).catch((err) => {
	console.log(err)
}).finally(() => {
	
})*/

const p1 = new Promise((resolve, reject) => {
	// 异步操作 ajax
	setTimeout(() => {
		// resolve("ok!")
		// resolve({ data: [], state: "ok 1" })
		reject("error! p1")
	}, 500)
})

function p2() {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			// resolve("ok!")
			resolve({ data: [], state: "ok 2" })
			// reject("error!")
		}, 10)
	})
}

const allP = Promise.all([
	myAjax({
		url: "http://yizhanketang.com:1010/api/v1/bmi"
	}),
	p1,
	p2()
])

const anyP = Promise.any([
	p1,
	myAjax({
		url: "http://yizhanketang.com:1010/api/v1/bmi456789"
	}),
	p2()
])

const raceP = Promise.race([
	p1,
	myAjax({
		url: "http://yizhanketang.com:1010/api/v1/bmi456789"
	}),
	p2()
])

raceP.then((res) => {
	console.log(res)
}).catch((err) => {
	console.log(err)
}).finally(() => {
	console.log("over!!!")
})


/*
anyP.then((res) => {
	console.log(res)
}).catch((err) => {
	console.log(err)
}).finally(() => {
	console.log("over!!!")
})

allP.then((res) => {
	console.log(res)
}).catch((err) => {
	console.log(err)
}).finally(() => {
	console.log("over!!!")
})
*/


/*

const x = 123
const px = Promise.reject(x)
px.catch((r) => {
	console.log(r)
})
const px = Promise.resolve(x)
px.then((r) => {
	console.log(r)
})


p1.then((result) => {
	// resolve
	// console.log(p1)
	console.log(result)
}).catch((error) => {
	// reject
	// console.log(p1)
	console.log(error)
}).finally(() => {
	console.log("over 1")
})

p2().then((res) => {
	console.log(res)
}).catch((e) => {
	console.log(e)
}).finally(() => {
	console.log("over 2")
})*/



/*
p1.then((result) => {
	// resolve
	// console.log(p1)
	console.log(result)
}).catch((error) => {
	// reject
	// console.log(p1)
	console.log(error)
})

p1.then((result) => {
	// resolve
	console.log(result)
}, (error) => {
	// reject
	console.log(error)
})
*/








